package com.zhao.reggie3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.reggie3.common.ProductException;
import com.zhao.reggie3.damain.Setmeal;
import com.zhao.reggie3.damain.SetmealDish;
import com.zhao.reggie3.dao.SetmealDao;
import com.zhao.reggie3.dto.SetmealDto;
import com.zhao.reggie3.service.DishService;
import com.zhao.reggie3.service.SetmealDishService;
import com.zhao.reggie3.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: zhao
 * @time: 2022/8/17 17:19
 */
@Service
@Slf4j
public class SetmealServiceimpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {


    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    @Transactional
    /**
     * @description 新增套餐同时保存菜品信息
     * @param [setmealDto]
     * @return void
     **/
    public void saveWithDish(SetmealDto setmealDto) {
       this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> collect = setmealDishes.stream().map((setmealDish) -> {
            Long setmealid = setmealDto.getId();
            setmealDish.setSetmealId(setmealid);
            return setmealDish;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(collect);
    }
    /**
     * @description//删除套餐，同时需要删除套餐和菜品的关联数据
     * @param
     * @return
     **/
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //select count(*) from setmeal where id in (1,2,3) and status = 1
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId,ids);
        lqw.eq(Setmeal::getStatus,1);

        int count = setmealService.count(lqw);
        if (count>0){
            //如果不能删除，抛出一个业务异常
            throw new ProductException("当前套餐菜品在出售,无法删除");
        }
        //如果可以删除，先删除套餐表中的数据---setmeal
        setmealService.removeByIds(ids);
        //删除关系表中的数据----setmeal_dish
        //delete from setmeal_dish where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> lqw1  = new LambdaQueryWrapper<>();
        lqw1.in(SetmealDish::getId,ids);

        setmealDishService.remove(lqw1);
    }
}